package com.powernode.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.domain.*;
import com.powernode.mapper.ProdMapper;
import com.powernode.mapper.ProdTagReferenceMapper;
import com.powernode.mapper.SkuMapper;
import com.powernode.service.ProdService;
import com.powernode.service.ProdTagReferenceService;
import com.powernode.service.SkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProdServiceImpl extends ServiceImpl<ProdMapper, Prod> implements ProdService{

    @Autowired
    private ProdMapper prodMapper;

    @Autowired
    private ProdTagReferenceService prodTagReferenceService;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private ProdTagReferenceMapper prodTagReferenceMapper;

    @Autowired
    private SkuService skuService;

    /**
     * 分页查询商品集合
     * @param page 分页参数和数据
     * @param prod 商品信息
     */
    @Override
    public void selectProdPage(Page<Prod> page, Prod prod) {
        prodMapper.selectPage(page, new LambdaQueryWrapper<Prod>()
                .eq(ObjectUtil.isNotEmpty(prod.getStatus()), Prod::getStatus, prod.getStatus())
                .like(StrUtil.isNotEmpty(prod.getProdName()), Prod::getProdName, prod.getProdName())
                .orderByDesc(Prod::getCreateTime));
    }

    @Override
    public List<Prod> selectProdListByIds(List<Long> ids) {
        return prodMapper.selectList(new LambdaQueryWrapper<Prod>()
            .eq(Prod::getStatus, 1)
                .in(Prod::getProdId, ids)
        );
    }

    @Override
    public Prod selectProdAndSkuList(Long prodId) {
        Prod prod = prodMapper.selectById(prodId);
        List<Sku> skuList = skuMapper.selectList(new LambdaQueryWrapper<Sku>()
                .eq(Sku::getProdId, prodId)
                .eq(Sku::getStatus , 1)
        );

        prod.setSkuList(skuList);
        return prod;
    }

    /**
     * 修改sku和prod库存数量
     * @param changeStock
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void changeStock(ChangeStock changeStock) {
        // 获取商品sku数量
        List<SkuChange> skuChangeList = changeStock.getSkuChangeList();

        skuChangeList.forEach(skuChange -> {
            Long skuId = skuChange.getSkuId();
            Sku sku = skuMapper.selectById(skuId);
            Integer version = sku.getVersion();
            int i = skuMapper.changeSkuStock(skuId, skuChange.getCount(), version);

            if (i <= 0) {
                throw new RuntimeException("库存数量不足");
            }
        });

        // 获取商品prod库存数量
        List<ProdChange> prodChangeList = changeStock.getProdChangeList();
        prodChangeList.forEach(prodChange -> {
            Long prodId = prodChange.getProdId();
            Prod prod = prodMapper.selectById(prodId);
            Integer version = prod.getVersion();
            int i = prodMapper.changeProdStock(prodId, prodChange.getCount(), version);

            if (i <= 0) {
                throw new RuntimeException("库存数量不足");
            }
        });

    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean save(Prod entity) {
        // 1. 新增商品
        Integer status = entity.getStatus();
        if (1 == status) {
            entity.setPutawayTime(new Date());
        }
        entity.setShopId(1L);
        entity.setSoldNum(0);
        entity.setCreateTime(new Date());
        entity.setUpdateTime(new Date());
        entity.setVersion(0);
        Prod.DeliveryModeVo deliveryModeVo = entity.getDeliveryModeVo();
        String deliverStr = JSONUtil.toJsonStr(deliveryModeVo);
        entity.setDeliveryMode(deliverStr);
        int i = prodMapper.insert(entity);

        if (i > 0) {
            // 2. 商品表添加成功则获取商品标识
            Long prodId = entity.getProdId();

            // 3. 收集关系记录的List
            List<ProdTagReference> prodTagReferences = new ArrayList<>();

            // 4. 新增商品和分组标签的关系表
            List<Long> tagList = entity.getTagList();
            if (CollectionUtil.isNotEmpty(tagList) && tagList.size() > 0) {
                for (Long tagId : tagList) {
                    ProdTagReference prodTagReference = new ProdTagReference();
                    prodTagReference.setProdId(prodId);
                    prodTagReference.setTagId(tagId);
                    prodTagReference.setCreateTime(new Date());
                    prodTagReference.setShopId(1L);
                    prodTagReference.setStatus(1);
                    prodTagReferences.add(prodTagReference);
                }

                prodTagReferenceService.saveBatch(prodTagReferences);
            }

            // 5. 获取商品sku对象集合
            List<Sku> skuList = entity.getSkuList();

            // 6. 判断商品sku对象集合是否有值
            if (CollectionUtil.isNotEmpty(skuList) && skuList.size() > 0) {
                skuList.forEach(sku -> {
                    // 获取
                    Integer stocks = sku.getStocks();
                    sku.setProdId(prodId);
                    sku.setActualStocks(stocks);
                    sku.setStocks(0);
                    sku.setUpdateTime(new Date());
                    sku.setRecTime(new Date());
                    sku.setIsDelete(0);
                    sku.setStatus(1);
                });

                skuService.saveBatch(skuList);
            }
        }

        return i > 0;
    }

    @Override
    public Prod getById(Serializable id) {
        // 1. 根据标识查询商品表
        Prod prod = prodMapper.selectById(id);

        // 2. 根据商品标识查询商品-分组标签关系集合
        List<ProdTagReference> prodTagReferences = prodTagReferenceMapper.selectList(new LambdaQueryWrapper<ProdTagReference>()
                .eq(ProdTagReference::getProdId, id));

        // 3.
        if (CollectionUtil.isNotEmpty(prodTagReferences) && prodTagReferences.size() > 0) {
            List<Long> tagIds = prodTagReferences.stream().map(ProdTagReference::getTagId).collect(Collectors.toList());
            prod.setTagList(tagIds);
        }

        // 4. 查询sku
        List<Sku> skuList= skuMapper.selectList(new LambdaQueryWrapper<Sku>().eq(Sku::getProdId, id));

        // 5.
        if (CollectionUtil.isNotEmpty(skuList) && skuList.size() > 0) {
            skuList.forEach(sku -> {
                sku.setStocks(sku.getActualStocks());
            });
            prod.setSkuList(skuList);
        }

        return prod;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean updateById(Prod entity) {
        // 1. 获取商品的id
        Long prodId = entity.getProdId();

        // 2. 删除原有的分组标签
        prodTagReferenceMapper.delete(new LambdaQueryWrapper<ProdTagReference>().eq(ProdTagReference::getProdId, prodId));

        // 3. 删除原有的sku
        skuMapper.delete(new LambdaQueryWrapper<Sku>().eq(Sku::getProdId, prodId));

        // 4. 增加
        List<ProdTagReference> prodTagReferences = new ArrayList<>();
        List<Long> tagList = entity.getTagList();
        if (CollectionUtil.isNotEmpty(tagList) && tagList.size() > 0) {
            for (Long tagId : tagList) {
                ProdTagReference prodTagReference = new ProdTagReference();
                prodTagReference.setProdId(prodId);
                prodTagReference.setTagId(tagId);
                prodTagReference.setCreateTime(new Date());
                prodTagReference.setShopId(1L);
                prodTagReference.setStatus(1);
                prodTagReferences.add(prodTagReference);
            }

            prodTagReferenceService.saveBatch(prodTagReferences);
        }

        List<Sku> skuList = entity.getSkuList();
        if (CollectionUtil.isNotEmpty(skuList) && skuList.size() > 0) {
            skuList.forEach(sku -> {
                // 获取
                Integer stocks = sku.getStocks();
                sku.setProdId(prodId);
                sku.setActualStocks(stocks);
                sku.setStocks(0);
                sku.setRecTime(new Date());
                sku.setIsDelete(0);
                sku.setStatus(1);
            });

            skuService.saveBatch(skuList);
        }

        entity.setUpdateTime(new Date());
        return prodMapper.updateById(entity) > 0;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public boolean removeByIds(Collection<? extends Serializable> idList) {
        // 1. 删除商品分组标签关系记录
        prodTagReferenceMapper.delete(new LambdaQueryWrapper<ProdTagReference>().in(ProdTagReference::getProdId, idList));

        // 2. 删除sku
        skuMapper.delete(new LambdaQueryWrapper<Sku>().in(Sku::getProdId, idList));
        // 3. 删除商品

        return prodMapper.delete(new LambdaQueryWrapper<Prod>().in(Prod::getProdId, idList)) > 0;
    }
}
